// 设置页面脚本

document.addEventListener('DOMContentLoaded', function() {
    // 初始化设置页面
    initSettingsPage();
});

// 默认设置
const defaultSettings = {
    focus_duration: 25,
    short_break_duration: 5,
    long_break_duration: 15,
    long_break_interval: 4,
    auto_start_break: true,
    auto_start_focus: false,
    notification: {
        enabled: true,
        type: 'detailed'
    },
    sound: {
        enabled: true,
        volume: 80
    },
    theme: {
        mode: 'light',
        color: 'blue'
    }
};

// 当前设置
let currentSettings = { ...defaultSettings };

// 初始化设置页面
function initSettingsPage() {
    // 加载当前设置
    loadSettings();
    
    // 注册导航项点击事件
    const navItems = document.querySelectorAll('.nav-item');
    navItems.forEach(item => {
        item.addEventListener('click', function() {
            switchSection(this.getAttribute('data-section'));
        });
    });
    
    // 注册滑块值实时更新
    initSliders();
    
    // 注册主题颜色选择
    initColorPicker();
    
    // 注册保存和重置按钮事件
    document.getElementById('save-settings').addEventListener('click', saveSettings);
    document.getElementById('reset-settings').addEventListener('click', confirmResetSettings);
    
    // 注册数据管理按钮事件
    document.getElementById('export-data').addEventListener('click', exportData);
    document.getElementById('import-data').addEventListener('change', handleFileSelect);
    document.getElementById('clear-sessions').addEventListener('click', confirmClearSessions);
    document.getElementById('clear-all-data').addEventListener('click', confirmClearAllData);
    
    // 注册对话框关闭按钮事件
    const closeButtons = document.querySelectorAll('.close-modal');
    closeButtons.forEach(button => {
        button.addEventListener('click', closeDialog);
    });
    
    // 点击对话框外部关闭
    window.addEventListener('click', function(event) {
        if (event.target.classList.contains('modal')) {
            closeDialog();
        }
    });
}

// 切换设置部分
function switchSection(sectionId) {
    // 更新导航项状态
    const navItems = document.querySelectorAll('.nav-item');
    navItems.forEach(item => {
        item.classList.toggle('active', item.getAttribute('data-section') === sectionId);
    });
    
    // 更新部分显示
    const sections = document.querySelectorAll('.settings-section');
    sections.forEach(section => {
        section.classList.toggle('active', section.id === sectionId);
    });
}

// 初始化滑块
function initSliders() {
    // 专注时长滑块
    const focusDurationSlider = document.getElementById('focus-duration');
    const focusDurationValue = document.getElementById('focus-duration-value');
    
    focusDurationSlider.addEventListener('input', function() {
        focusDurationValue.textContent = this.value;
    });
    
    // 短休息时长滑块
    const shortBreakDurationSlider = document.getElementById('short-break-duration');
    const shortBreakDurationValue = document.getElementById('short-break-duration-value');
    
    shortBreakDurationSlider.addEventListener('input', function() {
        shortBreakDurationValue.textContent = this.value;
    });
    
    // 长休息时长滑块
    const longBreakDurationSlider = document.getElementById('long-break-duration');
    const longBreakDurationValue = document.getElementById('long-break-duration-value');
    
    longBreakDurationSlider.addEventListener('input', function() {
        longBreakDurationValue.textContent = this.value;
    });
    
    // 长休息间隔滑块
    const longBreakIntervalSlider = document.getElementById('long-break-interval');
    const longBreakIntervalValue = document.getElementById('long-break-interval-value');
    
    longBreakIntervalSlider.addEventListener('input', function() {
        longBreakIntervalValue.textContent = this.value;
    });
    
    // 提示音音量滑块
    const soundVolumeSlider = document.getElementById('sound-volume');
    const soundVolumeValue = document.getElementById('sound-volume-value');
    
    soundVolumeSlider.addEventListener('input', function() {
        soundVolumeValue.textContent = `${this.value}%`;
    });
}

// 初始化颜色选择器
function initColorPicker() {
    const colorOptions = document.querySelectorAll('.color-option');
    
    colorOptions.forEach(option => {
        option.addEventListener('click', function() {
            // 移除所有选项的活动状态
            colorOptions.forEach(opt => opt.classList.remove('active'));
            // 添加当前选项的活动状态
            this.classList.add('active');
        });
    });
}

// 加载设置
async function loadSettings() {
    try {
        const settings = await api('/settings');
        currentSettings = settings;
        
        // 更新UI以反映当前设置
        updateSettingsUI(settings);
    } catch (error) {
        console.error('加载设置失败:', error);
        // 使用默认设置
        updateSettingsUI(defaultSettings);
    }
}

// 更新设置UI
function updateSettingsUI(settings) {
    // 时间设置
    document.getElementById('focus-duration').value = settings.focus_duration;
    document.getElementById('focus-duration-value').textContent = settings.focus_duration;
    
    document.getElementById('short-break-duration').value = settings.short_break_duration;
    document.getElementById('short-break-duration-value').textContent = settings.short_break_duration;
    
    document.getElementById('long-break-duration').value = settings.long_break_duration;
    document.getElementById('long-break-duration-value').textContent = settings.long_break_duration;
    
    document.getElementById('long-break-interval').value = settings.long_break_interval;
    document.getElementById('long-break-interval-value').textContent = settings.long_break_interval;
    
    document.getElementById('auto-start-break').checked = settings.auto_start_break;
    document.getElementById('auto-start-focus').checked = settings.auto_start_focus;
    
    // 通知设置
    const notification = typeof settings.notification === 'string' 
        ? JSON.parse(settings.notification) 
        : settings.notification;
    
    document.getElementById('enable-notification').checked = notification.enabled;
    document.getElementById('notification-type').value = notification.type || 'detailed';
    
    // 声音设置
    const sound = typeof settings.sound === 'string' 
        ? JSON.parse(settings.sound) 
        : settings.sound;
    
    document.getElementById('enable-sound').checked = sound.enabled;
    document.getElementById('sound-volume').value = sound.volume;
    document.getElementById('sound-volume-value').textContent = `${sound.volume}%`;
    
    // 主题设置
    const theme = typeof settings.theme === 'string' 
        ? JSON.parse(settings.theme) 
        : settings.theme;
    
    // 设置主题模式
    document.querySelector(`input[name="theme-mode"][value="${theme.mode}"]`).checked = true;
    
    // 设置主题颜色
    const colorOptions = document.querySelectorAll('.color-option');
    colorOptions.forEach(option => {
        option.classList.toggle('active', option.getAttribute('data-color') === theme.color);
    });
}

// 获取当前UI设置
function getSettingsFromUI() {
    const settings = {
        focus_duration: parseInt(document.getElementById('focus-duration').value),
        short_break_duration: parseInt(document.getElementById('short-break-duration').value),
        long_break_duration: parseInt(document.getElementById('long-break-duration').value),
        long_break_interval: parseInt(document.getElementById('long-break-interval').value),
        auto_start_break: document.getElementById('auto-start-break').checked,
        auto_start_focus: document.getElementById('auto-start-focus').checked,
        notification: JSON.stringify({
            enabled: document.getElementById('enable-notification').checked,
            type: document.getElementById('notification-type').value
        }),
        sound: JSON.stringify({
            enabled: document.getElementById('enable-sound').checked,
            volume: parseInt(document.getElementById('sound-volume').value)
        }),
        theme: JSON.stringify({
            mode: document.querySelector('input[name="theme-mode"]:checked').value,
            color: document.querySelector('.color-option.active').getAttribute('data-color')
        })
    };
    
    return settings;
}

// 保存设置
async function saveSettings() {
    const settings = getSettingsFromUI();
    
    try {
        await api('/settings', 'PUT', settings);
        
        // 更新当前设置
        currentSettings = settings;
        
        // 显示成功消息
        alert('设置已保存');
        
        // 应用主题设置
        applyThemeSettings(settings.theme);
    } catch (error) {
        console.error('保存设置失败:', error);
        alert('保存设置失败，请重试');
    }
}

// 应用主题设置
function applyThemeSettings(themeSettings) {
    const theme = typeof themeSettings === 'string' 
        ? JSON.parse(themeSettings) 
        : themeSettings;
    
    // 应用主题模式
    document.body.classList.remove('theme-light', 'theme-dark');
    
    if (theme.mode === 'auto') {
        // 检测系统主题偏好
        const prefersDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches;
        document.body.classList.add(prefersDarkMode ? 'theme-dark' : 'theme-light');
    } else {
        document.body.classList.add(`theme-${theme.mode}`);
    }
    
    // 存储主题设置到 localStorage
    localStorage.setItem('theme', theme.mode);
}

// 确认重置设置
function confirmResetSettings() {
    // 设置确认对话框
    document.getElementById('confirm-title').textContent = '重置设置';
    document.getElementById('confirm-message').textContent = '您确定要将所有设置重置为默认值吗？';
    
    // 设置确认按钮点击事件
    const confirmBtn = document.getElementById('confirm-ok');
    confirmBtn.onclick = resetSettings;
    
    // 显示对话框
    document.getElementById('confirm-dialog').style.display = 'block';
}

// 重置设置
function resetSettings() {
    // 更新UI为默认设置
    updateSettingsUI(defaultSettings);
    
    // 关闭对话框
    closeDialog();
}

// 导出数据
async function exportData() {
    try {
        // 获取所有数据
        const settings = await api('/settings');
        const goals = await api('/goals');
        const sessions = await api('/focus-sessions');
        const statistics = await api('/statistics');
        
        const exportData = {
            settings,
            goals,
            sessions,
            statistics,
            exportDate: new Date().toISOString()
        };
        
        // 创建下载链接
        const dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(exportData));
        const downloadAnchorNode = document.createElement('a');
        downloadAnchorNode.setAttribute("href", dataStr);
        downloadAnchorNode.setAttribute("download", `focus-timer-backup-${new Date().toISOString().slice(0, 10)}.json`);
        document.body.appendChild(downloadAnchorNode);
        downloadAnchorNode.click();
        downloadAnchorNode.remove();
    } catch (error) {
        console.error('导出数据失败:', error);
        alert('导出数据失败，请重试');
    }
}

// 处理文件选择
function handleFileSelect(event) {
    const file = event.target.files[0];
    if (!file) return;
    
    const reader = new FileReader();
    reader.onload = function(e) {
        try {
            const importData = JSON.parse(e.target.result);
            confirmImportData(importData);
        } catch (error) {
            console.error('解析导入文件失败:', error);
            alert('无效的备份文件格式');
        }
    };
    reader.readAsText(file);
}

// 确认导入数据
function confirmImportData(importData) {
    // 验证导入数据
    if (!importData.settings || !importData.goals || !importData.sessions || !importData.statistics) {
        alert('无效的备份文件格式');
        return;
    }
    
    // 设置确认对话框
    document.getElementById('confirm-title').textContent = '导入数据';
    document.getElementById('confirm-message').textContent = `您确定要从备份文件（${new Date(importData.exportDate).toLocaleDateString()}）中导入数据吗？这将覆盖当前数据。`;
    
    // 设置确认按钮点击事件
    const confirmBtn = document.getElementById('confirm-ok');
    confirmBtn.onclick = function() {
        importData(importData);
    };
    
    // 显示对话框
    document.getElementById('confirm-dialog').style.display = 'block';
}

// 导入数据
async function importData(importData) {
    try {
        // 导入设置
        await api('/settings', 'PUT', importData.settings);
        
        // 导入目标（先删除现有目标）
        const existingGoals = await api('/goals');
        for (const goal of existingGoals) {
            await api(`/goals/${goal.id}`, 'DELETE');
        }
        
        for (const goal of importData.goals) {
            await api('/goals', 'POST', {
                name: goal.name,
                description: goal.description,
                category: goal.category,
                target_time: goal.target_time,
                completed_time: goal.completed_time,
                completed: goal.completed,
                priority: goal.priority,
                deadline: goal.deadline,
                tags: goal.tags
            });
        }
        
        // 导入会话（先删除现有会话）
        const existingSessions = await api('/focus-sessions');
        for (const session of existingSessions) {
            await api(`/focus-sessions/${session.id}`, 'DELETE');
        }
        
        for (const session of importData.sessions) {
            await api('/focus-sessions', 'POST', {
                type: session.type,
                start_time: session.start_time,
                end_time: session.end_time,
                duration: session.duration,
                goal_id: session.goal_id,
                completed: session.completed,
                quality: session.quality,
                note: session.note
            });
        }
        
        // 关闭对话框
        closeDialog();
        
        // 刷新页面以应用导入的设置
        window.location.reload();
    } catch (error) {
        console.error('导入数据失败:', error);
        alert('导入数据失败，请重试');
        closeDialog();
    }
}

// 确认清除会话
function confirmClearSessions() {
    // 设置确认对话框
    document.getElementById('confirm-title').textContent = '清除专注记录';
    document.getElementById('confirm-message').textContent = '您确定要删除所有专注会话记录吗？此操作不可撤销。';
    
    // 设置确认按钮点击事件
    const confirmBtn = document.getElementById('confirm-ok');
    confirmBtn.onclick = clearSessions;
    
    // 显示对话框
    document.getElementById('confirm-dialog').style.display = 'block';
}

// 清除会话
async function clearSessions() {
    try {
        const sessions = await api('/focus-sessions');
        
        for (const session of sessions) {
            await api(`/focus-sessions/${session.id}`, 'DELETE');
        }
        
        closeDialog();
        alert('专注记录已清除');
    } catch (error) {
        console.error('清除专注记录失败:', error);
        alert('清除专注记录失败，请重试');
        closeDialog();
    }
}

// 确认清除所有数据
function confirmClearAllData() {
    // 设置确认对话框
    document.getElementById('confirm-title').textContent = '清除所有数据';
    document.getElementById('confirm-message').textContent = '警告：此操作将删除所有数据，包括专注记录、目标和设置。此操作不可撤销！';
    
    // 设置确认按钮点击事件
    const confirmBtn = document.getElementById('confirm-ok');
    confirmBtn.onclick = clearAllData;
    
    // 显示对话框
    document.getElementById('confirm-dialog').style.display = 'block';
}

// 清除所有数据
async function clearAllData() {
    try {
        // 清除会话
        const sessions = await api('/focus-sessions');
        for (const session of sessions) {
            await api(`/focus-sessions/${session.id}`, 'DELETE');
        }
        
        // 清除目标
        const goals = await api('/goals');
        for (const goal of goals) {
            await api(`/goals/${goal.id}`, 'DELETE');
        }
        
        // 重置设置
        await api('/settings', 'PUT', defaultSettings);
        
        closeDialog();
        alert('所有数据已清除');
        
        // 刷新页面以应用默认设置
        window.location.reload();
    } catch (error) {
        console.error('清除所有数据失败:', error);
        alert('清除所有数据失败，请重试');
        closeDialog();
    }
}

// 关闭对话框
function closeDialog() {
    document.getElementById('confirm-dialog').style.display = 'none';
} 